package com.zx.map.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zx.map.service.domain.agent.TransAgentDomain;
import com.zx.map.utils.CommonResponseUtils;
import com.zx.map.utils.MyBeanUtils;
import com.zx.map.utils.SUConstants;
import com.zx.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import sun.misc.BASE64Encoder;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.zx.map.common.ManageCommonHelper;
import com.zx.map.dao.model.MerchantCertificateInfo;
import com.zx.map.dao.model.StoreInfo;
import com.zx.map.service.AgentInfoService;
import com.zx.map.service.MerchantInfoService;
import com.zx.map.service.MerchantOfflineConfigInfoService;
import com.zx.map.service.SessionInfoService;
import com.zx.map.service.SettleCardInfoService;
import com.zx.map.service.StoreInfoService;
import com.zx.map.service.TodoTaskService;
import com.zx.map.service.domain.MerchantInfoDomain;
import com.zx.map.service.domain.TodoTaskDomain;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.MerchantInfoDetailModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.MerchantInfoTodoTask;
import com.zx.map.service.model.MerchantOfflineConfigInfoModel;
import com.zx.map.service.model.MerchantOfflineConfigInfoTodoTask;
import com.zx.map.service.model.SettleCardInfoModel;
import com.zx.map.service.model.TerminalInfoModel;
import com.zx.map.service.model.TodoTaskModel;
import com.zx.platform.service.domain.ManageSessionDomain;
import com.zx.platform.service.model.OperatorInfoModel;
import com.zx.platform.utils.AccountObjectSerializerUtil;
import com.zx.platform.utils.MD5Util;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.StrUtils;
import com.zx.scp.service.ImageCommonHelper;
import com.zx.scp.service.model.ImageSettleResponse;
import com.zx.scp.utils.MatrixToImageWriter;

/**
 * Created by IntelliJ IDEA. User: liubaojun Date: 15-05-12 Time: 下午12:00
 * 商户信息处理.
 */
@Controller
@RequestMapping("/manage/merchantInfo")
public class MerchantInfoController {
    /**
     * log
     */
    private static Logger log = Logger.getLogger(MerchantInfoController.class);

    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private TodoTaskService todoTaskService;
    @Autowired
    private AgentInfoService agentInfoService;
    @Autowired
    private SettleCardInfoService settleCardInfoService;
    @Autowired
    private SessionInfoService sessionInfoService;
    @Autowired
    private MerchantOfflineConfigInfoService merchantOfflineConfigInfoService;
    @Autowired
    private StoreInfoService storeInfoService;
    /**
     * 表单提交日期绑定
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                dateFormat, true));
    }

    /**
     * <h2>查看商户信息<h2>
     *
     * @param merchantInfo
     * @param model
     * @param request
     */
    @RequestMapping("/viewMerchantInfo")
    public String viewMerchantInfo(MerchantInfoModel merchantInfo, Model model,
                                   HttpServletRequest request) {
        try {

            MerchantInfoDetailModel m = merchantInfoService
                    .getMerchantDetail(merchantInfo.getMerchantId());
            List<TerminalInfoModel> terminalList = merchantInfoService
                    .getTerminalListByMerchantId(merchantInfo.getMerchantId());
            model.addAttribute("model", m);
            model.addAttribute("terminalList", terminalList);
            return "/jsp/map/merchantInfo/merchantInfoViewWindow";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/error";
        }
    }

    /**
     * 弹出的修改商户额度弹窗
     *
     * @param merchantInfo
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/limitChangeEdit")
    public String edit(MerchantInfoModel merchantInfo, Model model,
                       HttpServletRequest request) {
        try {
            MerchantInfoDetailModel m = merchantInfoService
                    .getMerchantDetail(merchantInfo.getMerchantId());
            model.addAttribute("model", m);
            return "/jsp/map/merchantInfo/limitChangeEdit";
        } catch (Exception e) {
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * <h2>修改商户信息<h2>
     *
     * @param merchantInfo
     * @param model
     * @param request
     */
    @RequestMapping("/editMerchantInfo")
    public String editMerchantInfo(MerchantInfoModel merchantInfo, Model model,
                                   HttpServletRequest request) {
        try {
            MerchantInfoTodoTask m = merchantInfoService
                    .transformMerchantDetailToTask(merchantInfo.getMerchantId());
            model.addAttribute("model", m);
            return "/jsp/map/merchantInfo/editMerchantiInfo";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/error";
        }
    }

    /**
     * @return
     */
    @RequestMapping("/isExistsSysAccount")
    @ResponseBody
    public Map isExistsSysAccount(MerchantInfoModel model) {
        try {
            List list = merchantInfoService.getListByModel(model);
            TodoTaskModel tmodel = new TodoTaskModel();
            tmodel.setTaskType("1");
            tmodel.setApproveStatus("0");
            List list1 = todoTaskService.getListByModel(tmodel);
            boolean flag = true;
            for (int i = 0; i < list1.size(); i++) {
                TodoTaskModel todoTaskModel = (TodoTaskModel) list1.get(i);
                MerchantInfoTodoTask merchantInfoTodoTaskTemp = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantInfoTodoTask.class);
                // 需要查出代理商系统账号
                MerchantInfoModel merchantInfoModel = merchantInfoTodoTaskTemp
                        .getMerchantInfoModel();
                String sysAccount = "";
                sysAccount = merchantInfoModel.getSysAccount() == null ? ""
                        : merchantInfoModel.getSysAccount();
                if (sysAccount.equals(model.getSysAccount())) {
                    flag = false;
                    break;
                }
            }
            if (list.size() > 0) {
                flag = false;
            }

            Map map = new HashMap();
            if (!flag) {
                map.put("success", false);
            } else {
                map.put("success", true);
            }
            model.setSuccess(true);
            log.debug("新增信息成功");
           return map;
        } catch (Exception e) {
            model.setSuccess(false);
            model.setMsg("失败");
            log.error("失败" + e.getMessage(), e);
        }
        return null;
    }

    /**
     * <h2>增加商户申请任务<h2>
     *
     * @param todoTask
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/merchantInfoApplyTaskAdd")
    public String merchantInfoApplyTaskAdd(HttpServletRequest request,
                                           @RequestParam("file") MultipartFile[] files,
                                           MerchantInfoTodoTask todoTask, Model model) throws IOException {
        try {
            int i = 0;
            // 设置上传文件的路径
            MerchantCertificateInfo merchantCertificateInfo = new MerchantCertificateInfo();
            // 查找当前操作员对应的代理商
            AgentInfoModel curAgentInfoModel =WebUtils.queryCurrentLoginAgentInfo(request);
            if (curAgentInfoModel != null) {
                todoTask.getMerchantInfoModel().setAgentId(
                        curAgentInfoModel.getAgentId());
            } else {
                model.addAttribute("errorMsg", "当前代理商不存在!");
                return "/jsp/platform/error";
            }
            for (MultipartFile f : files) {
                String fileName = f.getOriginalFilename();
                i++;
                if (fileName == null || fileName.length() == 0) {
                    continue;
                }
                // 对字节数组Base64编码
                BASE64Encoder encoder = new BASE64Encoder();
                ImageSettleResponse holdCard = null;
                if (i == 1) {
                    holdCard = ImageCommonHelper.getImageResponse(encoder
                            .encode(f.getBytes()), todoTask
                            .getMerchantInfoModel().getSysAccount());// 转换为base64编码
                    if ("0000".equals(holdCard.getReturnCode())) {
                        merchantCertificateInfo.setLegalIndentityImg(holdCard
                                .getImageKey());
                    } else {
                        throw new RuntimeException("图片处理异常");
                    }
                }
                if (i == 2) {
                    holdCard = ImageCommonHelper.getImageResponse(encoder
                            .encode(f.getBytes()), todoTask
                            .getMerchantInfoModel().getSysAccount());// 转换为base64编码
                    if ("0000".equals(holdCard.getReturnCode())) {
                        merchantCertificateInfo.setHoldIndentityCard(holdCard
                                .getImageKey());
                    } else {
                        throw new RuntimeException("图片处理异常");
                    }
                }
            }
            todoTask.setMerchantCertificateInfo(merchantCertificateInfo);
            // 直接把todoTask序列化
            Integer taskId = todoTaskService.addTodoTask(todoTask,
                    todoTask.getTodoTaskModel());
            model.addAttribute("taskId", "sucesses");
            return "redirect:/manage/merchantInfo/addMerchantInfoPre";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * @param files
     * @param model
     * @param todoTask
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/merchantInfoApplyTaskEdit")
    public String merchantInfoApplyTaskEdit(HttpServletRequest request,
                                            @RequestParam("file") MultipartFile[] files,
                                            MerchantInfoTodoTask todoTask, Model model) throws IOException {
        try {
            int i = 0;
            TodoTaskModel todoTaskModel = this.todoTaskService.getModelByKey(todoTask
                    .getTodoTaskModel().getTaskId());
            MerchantInfoTodoTask merchantInfoTodoTaskTemp = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantInfoTodoTask.class);
            MerchantCertificateInfo merchantCertificateInfo = merchantInfoTodoTaskTemp
                    .getMerchantCertificateInfo();
            for (MultipartFile f : files) {
                i++;
                String fileName = f.getOriginalFilename();
                if (fileName == null || fileName.length() == 0) {
                    continue;
                }
                // 对字节数组Base64编码
                BASE64Encoder encoder = new BASE64Encoder();
                ImageSettleResponse holdCard = null;
                if (i == 1) {
                    holdCard = ImageCommonHelper.getImageResponse(encoder
                            .encode(f.getBytes()), merchantInfoTodoTaskTemp
                            .getMerchantInfoModel().getSysAccount());// 转换为base64编码
                    if ("0000".equals(holdCard.getReturnCode())) {
                        merchantCertificateInfo.setLegalIndentityImg(holdCard
                                .getImageKey());
                    } else {
                        throw new RuntimeException("图片处理异常");
                    }
                }
                if (i == 2) {
                    holdCard = ImageCommonHelper.getImageResponse(encoder
                            .encode(f.getBytes()), merchantInfoTodoTaskTemp
                            .getMerchantInfoModel().getSysAccount());// 转换为base64编码
                    if ("0000".equals(holdCard.getReturnCode())) {
                        merchantCertificateInfo.setHoldIndentityCard(holdCard
                                .getImageKey());
                    } else {
                        throw new RuntimeException("图片处理异常");
                    }
                }
            }

            todoTask.setMerchantCertificateInfo(merchantCertificateInfo);
            // 直接把todoTask序列化
            Integer taskId = todoTaskService.updateTodoTask(todoTask,
                    todoTask.getTodoTaskModel());
            model.addAttribute("taskId", taskId);
            return "redirect:/manage/merchantInfo/refuseMerchant";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * <h2>二维码申请流程<h2>
     *
     * @param merchantOfflineConfigInfoModel
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/applyQR")
    public String applyQR(MerchantOfflineConfigInfoModel merchantOfflineConfigInfoModel, HttpServletRequest request, Model model) throws IOException {
        try {
            // 查找当前操作员对应的代理商
            AgentInfoModel cuAgentInfoModel= WebUtils.queryCurrentLoginAgentInfo(request);
            /*if (cuAgentInfoModel == null) {
                model.addAttribute("errorMsg", "当前代理商不存在!");
                return "/jsp/platform/error";
            }*/
            model.addAttribute("model", merchantOfflineConfigInfoModel);
            return "/jsp/map/merchantInfo/applyQrPre";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * <h2>二维码申请流程<h2>
     *
     * @param merchantOfflineConfigInfoModel
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/dealApplyQR")
    public String dealApplyQR(HttpServletRequest request,
                              @RequestParam("file") MultipartFile[] files,
                              MerchantOfflineConfigInfoModel merchantOfflineConfigInfoModel, Model model) throws IOException {
        try {
            int i = 0;
            // 查找当前操作员对应的代理商
            ManageSessionDomain userinfo = (ManageSessionDomain) request
                    .getSession().getAttribute("_LOGONUSER_");
            OperatorInfoModel curOperatorInfo = userinfo.getOperatorInfoModel();
            AgentInfoModel agentInfoModel = agentInfoService
                    .getAgentInfoModelBySysAccount(curOperatorInfo
                            .getLoginName());
            /*if (agentInfoModel == null) {
                model.addAttribute("errorMsg", "当前代理商不存在!");
                return "/jsp/platform/error";
            }*/
            for (MultipartFile f : files) {
                String fileName = f.getOriginalFilename();
                i++;
                if (fileName == null || fileName.length() == 0) {
                    continue;
                }
                // 对字节数组Base64编码
                BASE64Encoder encoder = new BASE64Encoder();
                ImageSettleResponse imageSettle = null;
                if (i == 1) {
                    imageSettle = ImageCommonHelper.getImageResponse(encoder
                            .encode(f.getBytes()), merchantOfflineConfigInfoModel.getMerchantSysAccount());// 转换为base64编码
                    if ("0000".equals(imageSettle.getReturnCode())) {
                        merchantOfflineConfigInfoModel.setLegalImg(imageSettle
                                .getImageKey());
                    } else {
                        throw new RuntimeException("图片处理异常");
                    }
                }
            }
            // 直接把todoTask序列化
            TodoTaskModel todoTaskModel = new TodoTaskModel();
            todoTaskModel.setCreateDate(new Date());
            todoTaskModel.setTaskKey("");
            todoTaskModel.setTaskType("8");//1、	商户新增  	2、	终端绑定    3、	终端解绑
            todoTaskModel.setTaskOperatorType("2");  //1、	新增2、	修改
            todoTaskModel.setApplyType(userinfo.getOperatorInfoModel().getOperatorType()); //1、	系统人员发起				2、	代理人发起
            todoTaskModel.setApplyOperator(userinfo.getOperatorInfoModel().getLoginName());
            todoTaskModel.setApproveStatus("0");  //0:未审批,1审批通过,2审批拒绝
            Integer taskId = todoTaskService.addTodoTask(merchantOfflineConfigInfoModel,
                    todoTaskModel);
            model.addAttribute("operateType", Boolean.TRUE);
            model.addAttribute("model", merchantOfflineConfigInfoModel);
            return "/jsp/map/merchantInfo/applyQrPre";
        } catch (Exception e) {
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * 二维码申请审核页面 edit by wenjw 2015.5.14
     *
     * @param domain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/applyQRApproveTask")
    public String applyQRApproveTask(TodoTaskDomain domain, Model model,
                                     HttpServletRequest request) {

        try {// 初始化信息
            Integer pageNum = domain.getPageNum();
            Integer pageSize = domain.getPageSize();
            Integer pageCount = domain.getPageCount();
            if (null == pageNum) {
                pageNum = 1;
            }
            if (null == pageSize) {
                pageSize = 10;
            }
            // 任务类型是1
            domain.setTaskType("8");
            Map map = todoTaskService
                    .getPageByDomain(pageSize, pageNum, domain);
            List<TodoTaskModel> todoTaskModelList = (List<TodoTaskModel>) map
                    .get("list");
            // 转换
            List<MerchantOfflineConfigInfoTodoTask> modelList = new ArrayList<MerchantOfflineConfigInfoTodoTask>();
            for (TodoTaskModel todoTaskModel : todoTaskModelList) {
                MerchantOfflineConfigInfoTodoTask task = new MerchantOfflineConfigInfoTodoTask();
                MerchantOfflineConfigInfoModel temp = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantOfflineConfigInfoModel.class);
                task.setMerchantOfflineConfigInfoModel(temp);
                task.setTodoTaskModel(todoTaskModel);
                modelList.add(task);
            }
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            model.addAttribute("list", modelList);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            model.addAttribute("model", domain);
            return "/jsp/map/merchantInfo/applyQrApproveTask";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * 二维码审核查看功能
     *
     * @param domain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/applyQrApproveTaskView")
    public String applyQrApproveTaskView(TodoTaskDomain domain,
                                         Model model, HttpServletRequest request) {

        try {
            TodoTaskModel todoTaskModel = todoTaskService.getModelByKey(domain.getTaskId());
            MerchantOfflineConfigInfoModel merchantOfflineConfigInfoModel = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantOfflineConfigInfoModel.class);
            // 获得商户信息
            model.addAttribute("model", merchantOfflineConfigInfoModel);
            return "/jsp/map/merchantInfo/applyQrTaskView";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * 二维码下载功能
     *
     * @param merchantInfoModel
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/downloadQr")
    public void downloadQr(MerchantInfoModel merchantInfoModel,
                           Model model, HttpServletRequest request, HttpServletResponse response) {

        try {
            MerchantOfflineConfigInfoModel temp = merchantOfflineConfigInfoService.getModelByKey(merchantInfoModel.getMerchantId());
            if (null != temp) {
                OutputStream os = response.getOutputStream();// 取得输出流
                response.reset();// 清空输出流
                response.setHeader("Pragma", "No-cache");
                response.setHeader("Cache-Control", "no-cache");
                response.setDateHeader("Expires", 0);
                response.setContentType("image/jpeg");
                response.setHeader("Content-disposition", "attachment; filename="
                        + URLEncoder.encode(temp.getMerchantShortName() + ".jpg", "UTF-8"));// 设定输出文件头
                int width = 640; // 二维码图片宽度
                int height = 640; // 二维码图片高度
                String format = "jpg";// 二维码的图片格式
                Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
                hints.put(EncodeHintType.CHARACTER_SET, "utf-8");   // 内容所使用字符集编码
                BitMatrix bitMatrix = new MultiFormatWriter().encode(temp.getOfflinePayUrl(), BarcodeFormat.QR_CODE, width, height, hints);
                // 生成二维码
                MatrixToImageWriter.writeToStream(bitMatrix, format, os);
                //输出
                os.close();
            }
        } catch (Exception e) {
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
        }
    }

    /**
     * @param merchantInfo
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/addMerchantInfoPre")
    public String addMerchantInfoPre(MerchantInfoModel merchantInfo,
                                     Model model, HttpServletRequest request) throws IOException {
        String taskId = request.getParameter("taskId") == null ? ""
                : (String) request.getParameter("taskId");
        model.addAttribute("taskId", taskId);
        return "/jsp/map/merchantInfo/addMerchantInfoPre";

    }

    /**
     * 查询商户列表
     *
     * @param domain
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/queryMerchantInfoList")
    public String queryMerchantInfoList(MerchantInfoDomain domain, Model model,
                                        HttpServletRequest request) {
        // 初始化信息
        try {
            Integer pageNum = domain.getPageNum();
            Integer pageSize = domain.getPageSize();
            pageNum = pageNum == null ? 1 : pageNum;
            pageSize = pageSize == null ? SUConstants.PAGE_COUNT : pageSize;
            domain.setPageNum(pageNum);
            domain.setPageSize(pageSize);

            // 查找当前操作员对应的代理商,系统管理员不加条件，代理商仅能查询所属自己的客商
            AgentInfoModel cuAgentInfoModel= WebUtils.queryCurrentLoginAgentInfo(request);
            if(cuAgentInfoModel==null){//平台
            } else {
                cuAgentInfoModel.setHasSelf(true);
            }

            // 查询特定状态
            Map map = merchantInfoService.getPageByDomain(domain,cuAgentInfoModel);
            List<MerchantInfoModel> merchantInfoModelList = (List<MerchantInfoModel>) map
                    .get("list");
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            model.addAttribute("list", merchantInfoModelList);
            model.addAttribute("model", domain);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            return "/jsp/map/merchantInfo/merchantInfoList";

        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/error";
        }
    }

    /**
     * 简单版本的商户列表
     *
     * @param domain
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/querySimpleMerchantInfoList")
    public String querySimpleMerchantInfoList(MerchantInfoDomain domain,
                                              Model model, HttpServletRequest request) {
        // 初始化信息
        try {
            Integer pageNum = domain.getPageNum();
            Integer pageSize = domain.getPageSize();
            pageNum = pageNum == null ? 1 : pageNum;
            pageSize = pageSize == null ? SUConstants.PAGE_COUNT : pageSize;
            domain.setPageNum(pageNum);
            domain.setPageSize(pageSize);

            // 查找当前操作员对应的代理商,系统管理员不加条件，代理商仅能查询所属自己的客商
            AgentInfoModel cuAgentInfoModel= WebUtils.queryCurrentLoginAgentInfo(request);
            //作为查询条件查询直属商户
            if(domain.getIsDirect()>0&&cuAgentInfoModel!=null){
               domain.setAgentId(cuAgentInfoModel.getAgentId());
            }

            if(cuAgentInfoModel==null){//平台
            } else {
                cuAgentInfoModel.setHasSelf(true);
            }
            // 查询特定状态
            Map map = merchantInfoService.getPageByDomain(domain,cuAgentInfoModel);
            List<MerchantInfoModel> merchantInfoModelList = (List<MerchantInfoModel>) map.get("list");
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            model.addAttribute("list", merchantInfoModelList);
            model.addAttribute("model", domain);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            return "/jsp/map/merchantInfo/merchantInfoSimpleList";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/error";
        }
    }

    /**
     * 商户终端绑定
     *
     * @param domain
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/querySimpleMerchantInfoForBind")
    public String querySimpleMerchantInfoForBind(MerchantInfoDomain domain,
                                                 Model model, HttpServletRequest request) {
        // 初始化信息
        try {
            Integer pageNum = domain.getPageNum();
            Integer pageSize = domain.getPageSize();
            pageNum = pageNum == null ? 1 : pageNum;
            pageSize = pageSize == null ? SUConstants.PAGE_COUNT : pageSize;
            domain.setPageNum(pageNum);
            domain.setPageSize(pageSize);

            // 查找当前操作员对应的代理商,系统管理员不加条件，代理商仅能查询所属自己的客商
            AgentInfoModel cuAgentInfoModel= WebUtils.queryCurrentLoginAgentInfo(request);
            if(cuAgentInfoModel==null){//平台
            } else {
                cuAgentInfoModel.setHasSelf(true);
            }
            // 查询特定状态
            Map map = merchantInfoService.getPageByDomain(domain,cuAgentInfoModel);
            List<MerchantInfoModel> merchantInfoModelList = (List<MerchantInfoModel>) map.get("list");
            for (MerchantInfoModel oo : merchantInfoModelList) {
                MerchantOfflineConfigInfoModel temp = merchantOfflineConfigInfoService.getModelByKey(oo.getMerchantId());
                if (null != temp && StringUtils.isNotBlank(temp.getMerchantId())) { //已经申请线下扫码
                    oo.setOfflineFlag(Boolean.TRUE);
                } else {
                    oo.setOfflineFlag(Boolean.FALSE);
                }
            }
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            model.addAttribute("list", merchantInfoModelList);
            model.addAttribute("model", domain);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            return "/jsp/map/merchantInfo/merchantInfoSimpleForBind";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/error";
        }
    }

    /**
     * 更新商户状态
     *
     * @param merchantInfoModel
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/updateMerchantInfo")
    @ResponseBody
    public MerchantInfoModel updateMerchantInfo(
            MerchantInfoModel merchantInfoModel, String operatorType,
            Model model, HttpServletRequest request) {
        try {
            merchantInfoService.update(merchantInfoModel);
            if ("L".equalsIgnoreCase(operatorType))// 如果是锁定 需要将前端用户登陆信息删除
            {
                sessionInfoService.delete(merchantInfoModel.getSysAccount());
            }
            merchantInfoModel.setSuccess(true);
            merchantInfoModel.setMsg("修改成功");
        } catch (Exception e) {
            log.error("内部异常", e);
            merchantInfoModel.setSuccess(false);
            merchantInfoModel.setMsg("修改失败");
        }
        return merchantInfoModel;
    }

    /**
     * @return
     */
    @RequestMapping("/replyMerchantInfo")
    public
    @ResponseBody
    Map replyMerchantInfo(HttpServletRequest request) {
        Map map = new HashMap();
        try {
            String merchantId = request.getParameter("merchantId");
            String content = request.getParameter("content");
            String applySatus = request.getParameter("applySatus");
            MerchantInfoModel m = new MerchantInfoModel();
            m.setMerchantId(merchantId);
            m.setStatus(applySatus);
            merchantInfoService.update(m);
            map.put("state", "1");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", "0");
            log.error("查询相关信息失败" + e.getMessage(), e);
        }
        return map;
    }

    /**
     * 密码重置
     *
     * @return
     */
    @RequestMapping("/resetPassword")
    public
    @ResponseBody
    Map resetPassword(String merchantId,
                      HttpServletRequest request) {
        Map map = new HashMap();
        try {
            MerchantInfoModel m = new MerchantInfoModel();
            m.setMerchantId(merchantId);
            m.setSysPassword(PmpUtils.encoderByMD5(MD5Util
                    .getMD5Str(ManageCommonHelper.DEFAULT_LOGINPASSWORD)));
            merchantInfoService.update(m);
            map.put("state", "1");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", "0");
            log.error("查询相关信息失败" + e.getMessage(), e);
        }
        return map;
    }

    /**
     * 重置交易密码
     *
     * @return
     */
    @RequestMapping("/resetPayPassword")
    public
    @ResponseBody
    Map resetPayPassword(String merchantId,
                         HttpServletRequest request) {
        Map map = new HashMap();
        try {
            MerchantInfoModel m = new MerchantInfoModel();
            m.setMerchantId(merchantId);
            m.setTradePassword(PmpUtils.encoderByMD5(MD5Util
                    .getMD5Str(ManageCommonHelper.DEFAULT_TRADEPASSWORD)));
            merchantInfoService.update(m);
            map.put("state", "1");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", "0");
            log.error("查询相关信息失败" + e.getMessage(), e);
        }
        return map;
    }

    /**
     * 被拒商户列表
     *
     * @param domain
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/refuseMerchant")
    public String refuseMerchant(TodoTaskDomain domain, Model model,
                                 HttpServletRequest request) {
        try {// 初始化信息
            Integer pageNum = domain.getPageNum();
            Integer pageSize = domain.getPageSize();
            if (null == pageNum) {
                pageNum = 1;
            }
            if (null == pageSize) {
                pageSize = 10;
            }
            // 查找当前操作员对应的代理商,系统管理员不加条件，代理商仅能查询所属自己的客商
            ManageSessionDomain userinfo = (ManageSessionDomain) request
                    .getSession().getAttribute("_LOGONUSER_");
            OperatorInfoModel curOperatorInfo = userinfo.getOperatorInfoModel();
            AgentInfoModel agentInfoModel = agentInfoService
                    .getAgentInfoModelBySysAccount(curOperatorInfo
                            .getLoginName());
            if (agentInfoModel != null) {
                domain.setApplyOperator(curOperatorInfo.getLoginName());// 代理对应的操作员账号
                // 登录名
                // 也就是代理系统账号
            } else {
                domain.setApplyOperator("none");
            }
            // 任务类型是1
            domain.setTaskType(ManageCommonHelper.TASKTYPE_MERCHANTADD);
            // approveStatus 0:待审核 1：审核通过 2：审核拒绝
            domain.setApproveStatus(ManageCommonHelper.APPROVESTATUS_REFUSE);
            Map map = todoTaskService
                    .getPageByDomain(pageSize, pageNum, domain);
            List<TodoTaskModel> todoTaskModelList = (List<TodoTaskModel>) map
                    .get("list");
            // 转换
            List<MerchantInfoTodoTask> modelList = new ArrayList();
            for (TodoTaskModel todoTaskModel : todoTaskModelList) {
                MerchantInfoTodoTask merchantInfoTodoTask = new MerchantInfoTodoTask();
                merchantInfoTodoTask.setTodoTaskModel(todoTaskModel);
                MerchantInfoTodoTask merchantInfoTodoTaskTemp = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantInfoTodoTask.class);
                // 查找代理账号 edit by wenjw 2015.6.2
                // 需要查出代理商系统账号
                MerchantInfoModel merchantInfoModel = merchantInfoTodoTaskTemp
                        .getMerchantInfoModel();
                if (merchantInfoModel != null) {
                    String agentId = merchantInfoModel.getAgentId();
                    if (StrUtils.isNotEmpty(agentId)) {
                        AgentInfoModel agent = agentInfoService
                                .getModelByKey(agentId);
                        if (agentInfoModel != null) {
                            merchantInfoModel.setAgentSysAccount(agent
                                    .getSysAccount());
                        }
                    }
                }
                merchantInfoTodoTask.setMerchantInfoModel(merchantInfoModel);
                merchantInfoTodoTask
                        .setSettleCardInfoModel(merchantInfoTodoTaskTemp
                                .getSettleCardInfoModel());
                modelList.add(merchantInfoTodoTask);
            }
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            model.addAttribute("list", modelList);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            model.addAttribute("model", domain);
            return "/jsp/map/merchantInfo/merchantInfoRefuseList";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }

    }

    /**
     * 商户信息审核页面 edit by wenjw 2015.5.14
     *
     * @param domain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/merchantInfoApproveTask")
    public String merchantInfoApproveTask(TodoTaskDomain domain, Model model,
                                          HttpServletRequest request) {

        try {// 初始化信息
            Integer pageNum = domain.getPageNum();
            Integer pageSize = domain.getPageSize();
            Integer pageCount = domain.getPageCount();
            if (null == pageNum) {
                pageNum = 1;
            }
            if (null == pageSize) {
                pageSize = 10;
            }

            // 任务类型是1
            domain.setTaskType("1");
            Map map = todoTaskService
                    .getPageByDomain(pageSize, pageNum, domain);
            List<TodoTaskModel> todoTaskModelList = (List<TodoTaskModel>) map
                    .get("list");
            // 转换
            List<MerchantInfoTodoTask> modelList = new ArrayList();
            for (TodoTaskModel todoTaskModel : todoTaskModelList) {
                MerchantInfoTodoTask merchantInfoTodoTask = new MerchantInfoTodoTask();
                merchantInfoTodoTask.setTodoTaskModel(todoTaskModel);
                MerchantInfoTodoTask merchantInfoTodoTaskTemp = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantInfoTodoTask.class);
                
                // 需要查出代理商系统账号
                MerchantInfoModel merchantInfoModel = merchantInfoTodoTaskTemp
                        .getMerchantInfoModel();
               
//                if (merchantInfoModel != null) {
//                    String agentId = merchantInfoModel.getAgentId();
//                    if (StrUtils.isNotEmpty(agentId)) {
//                        AgentInfoModel agentInfoModel = agentInfoService
//                                .getModelByKey(agentId);
//                        if (agentInfoModel != null) {
//                            merchantInfoModel.setAgentSysAccount(agentInfoModel
//                                    .getSysAccount());
//                        }
//                    }
//                }

                merchantInfoTodoTask
                        .setMerchantInfoModel(merchantInfoTodoTaskTemp
                                .getMerchantInfoModel());
//                merchantInfoTodoTask
//                        .setSettleCardInfoModel(merchantInfoTodoTaskTemp
//                                .getSettleCardInfoModel());
                modelList.add(merchantInfoTodoTask);
            }
            int recordCount = Integer.valueOf(map.get("count").toString());
            // 页面信息
            if (pageSize * pageNum > recordCount + pageSize - 1) {
                pageNum = 1;
            }
            
            model.addAttribute("list", modelList);
            model.addAttribute("pageNum", pageNum);
            model.addAttribute("pageSize", pageSize);
            model.addAttribute("pageCount",
                    PmpUtils.getPageCount(recordCount, pageSize));
            model.addAttribute("recordCount", recordCount);
            model.addAttribute("model", domain);
            
            return "/jsp/map/merchantInfo/merchantInfoApproveTask";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * 商户信息审核页面 edit by bj.liu 2015.5.20
     *
     * @param domain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/merchantInfoApproveTaskView")
    public String merchantInfoApproveTaskView(TodoTaskDomain domain,
                                              Model model, HttpServletRequest request) {

        try {
            int taskId = domain.getTaskId();
            TodoTaskModel todoTaskModel = todoTaskService.getModelByKey(taskId);
            MerchantInfoTodoTask merchantInfoTodoTaskTemp = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantInfoTodoTask.class);
            // 获得商户信息
            model.addAttribute("model",
                    merchantInfoTodoTaskTemp.getMerchantInfoModel());
            StoreInfo storeInfo = storeInfoService.find(merchantInfoTodoTaskTemp.getMerchantInfoModel().getMerchantId());
            
            model.addAttribute("model1", storeInfo);
            model.addAttribute("model2",
                    merchantInfoTodoTaskTemp.getSettleCardInfoModel());
//            model.addAttribute("terminalList",
//                    merchantInfoTodoTaskTemp.getTerminalModelList());

            return "/jsp/map/merchantInfo/merchantInfoTaskView";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * 商户信息审核页面 edit by bj.liu 2015.5.20
     *
     * @param domain
     * @param model
     * @param request
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/refuseMerchantEdit")
    public String refuseMerchantEdit(TodoTaskDomain domain, Model model,
                                     HttpServletRequest request) {

        try {
            int taskId = domain.getTaskId();
            TodoTaskModel todoTaskModel = todoTaskService.getModelByKey(taskId);
            MerchantInfoTodoTask merchantInfoTodoTaskTemp = MyBeanUtils.jsonToBean(todoTaskModel.getTaskInfo(),MerchantInfoTodoTask.class);
            // 重新设置todoTask
            merchantInfoTodoTaskTemp.setTodoTaskModel(todoTaskModel);
            model.addAttribute("model", merchantInfoTodoTaskTemp);
            model.addAttribute("editFlag", "true");
            return "/jsp/map/merchantInfo/editMerchantiInfoApprove";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/jsp/platform/error";
        }
    }

    /**
     * @return
     */
    @RequestMapping("/existMerchantInfo")
    public
    @ResponseBody
    MerchantInfoModel existMerchantInfo(
            MerchantInfoModel model) {
        try {
            List list = merchantInfoService.getListByModel(model);
            if (list != null && list.size() > 0) {
                model.setMsg("1");
            } else {
                model.setMsg("2");
            }
            model.setSuccess(true);
            log.debug("存在商户");
        } catch (Exception e) {
            model.setSuccess(false);
            model.setMsg("查询商户失败");
            log.error("查询商户失败" + e.getMessage(), e);
        }
        return model;
    }

    /**
     * @return
     */
    @RequestMapping("/existMerchantInfoAndSettleCard")
    public
    @ResponseBody
    MerchantInfoModel existMerchantInfoAndSettleCard(
            MerchantInfoModel model) {
        try {
            MerchantInfoModel querymodel = merchantInfoService
                    .getMerchantInfoModelBySysAccount(model.getSysAccount());
            if (querymodel != null) {
                String merchantId = querymodel.getMerchantId();
                SettleCardInfoModel sModel = new SettleCardInfoModel();
                sModel.setSubjectType("1");
                sModel.setSubjectId(merchantId);
                sModel = settleCardInfoService.getModelByInfo(sModel);
                if (sModel == null) {
                    model.setMsg("3");
                } else {
                    model.setMsg("1");
                }

            } else {
                model.setMsg("2");
            }
            model.setSuccess(true);
            log.debug("存在商户");
        } catch (Exception e) {
            model.setSuccess(false);
            model.setMsg("查询商户失败");
            log.error("查询商户失败" + e.getMessage(), e);
        }
        return model;
    }

    /**
     * <h2>修改商户信息<h2>
     *
     * @param merchantInfo
     * @param model
     * @param request
     */
    @RequestMapping("/modifyMerchantInfoWindow")
    public String modifyMerchantInfoWindow(MerchantInfoModel merchantInfo,
                                           Model model, HttpServletRequest request) {
        try {

            MerchantInfoDetailModel m = merchantInfoService
                    .getMerchantDetail(merchantInfo.getMerchantId());
            List<TerminalInfoModel> terminalList = merchantInfoService
                    .getTerminalListByMerchantId(merchantInfo.getMerchantId());
            model.addAttribute("model", m);
            model.addAttribute("terminalList", terminalList);
            return "/jsp/map/merchantInfo/modifyMerchantInfoWindow";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/error";
        }
    }

    /**
     * <h2>修改商户信息<h2>
     *
     * @param model
     * @param request
     */
    @RequestMapping("/saveMerchantInfo")
    public String saveMerchantInfo(HttpServletRequest request,
                                   @RequestParam("file") MultipartFile[] files,
                                   MerchantInfoDetailModel detail, Model model) {
        try {
            int i = 0;
            for (MultipartFile f : files) {
                i++;
                String fileName = f.getOriginalFilename();
                if (fileName == null || fileName.length() == 0) {
                    continue;
                }
                // 对字节数组Base64编码
                BASE64Encoder encoder = new BASE64Encoder();
                ImageSettleResponse holdCard = null;
                if (i == 1) {
                    holdCard = ImageCommonHelper.getImageResponse(
                            encoder.encode(f.getBytes()),
                            detail.getSysAccount());// 转换为base64编码
                    if ("0000".equals(holdCard.getReturnCode())) {
                        detail.setLegalIndentityImg(holdCard.getImageKey());
                    } else {
                        throw new RuntimeException("图片处理异常");
                    }
                }
                if (i == 2) {
                    holdCard = ImageCommonHelper.getImageResponse(
                            encoder.encode(f.getBytes()),
                            detail.getSysAccount());// 转换为base64编码
                    if ("0000".equals(holdCard.getReturnCode())) {
                        detail.setHoldIndentityCard(holdCard.getImageKey());
                    } else {
                        throw new RuntimeException("图片处理异常");
                    }
                }
            }
            merchantInfoService.saveDetail(detail);
            model.addAttribute("merchantId", detail.getMerchantId());
            return "redirect:/manage/merchantInfo/modifyMerchantInfoWindow";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("内部异常", e);
            model.addAttribute("errorMsg", "出错了");
            return "/error";
        }
    }

    //商户转让
    @RequestMapping("/transMerchantInfo")
    public String transMerchantInfo(Model model,HttpServletRequest request){
        return "jsp/map/merchantInfo/transMerchantInfo";
    }

    @RequestMapping("/transMerchant")
    @ResponseBody
    public Map<String,Object> transMerchant(TransAgentDomain transMerchantDomain, Model model,
                                            HttpServletRequest request){
        try {
            AgentInfoModel curAgentInfoModel = WebUtils.queryCurrentLoginAgentInfo(request);
            return merchantInfoService.transMerchant(transMerchantDomain,curAgentInfoModel);
        }catch (Exception e){
            return CommonResponseUtils.failureResponse(SUConstants.SERVER_ERROR);
        }
    }
}
